<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Frontend_Controller extends Template_Controller {

	/**
	 *
	 * @property User $user
	 * @property Session $session
	 * @property A2 $acl
	 */
	protected $user = FALSE;
	protected $config;
	public $session = FALSE;
	public $acl;
	public $template = 'index';
	public $role_required = FALSE;
	public $history = TRUE;

	public function __construct() {
		parent::__construct();

		$this->config = Kohana::config('cms');
    $this->acl = A2::instance();
    $this->auth = $this->acl->a1;
		$this->session = new Session;
    $islogged = $this->auth->logged_in();
		// Redirect to login page if required
		if ($this->role_required !== FALSE AND $this->role_required !== Kohana::config('a2.quest_role')) {
			if (!$islogged) {
				message::add(Kohana::lang('auth.message.must_login'), 'error');
				//$this->keep_referrer(TRUE);
				url::redirect(Router::uri('auth', array('method'=>'login')));
			}
			elseif (!$this->acl->has_role($this->role_required)) {
				message::add(Kohana::lang('auth.message.role_not_enouth'), 'error');
				Event::run('admin.access_denied');
			}
		}
		// Keep User_Model in $this->user
		if ($islogged) {
			$this->user = $this->acl->get_user();
			$this->template->set_global('user_id', $this->user->id);
			$this->template->set_global('user_name', $this->user->username);
		}

		// Set global template variable with locale value ('en', 'ru', 'ua' etc)
		$this->template->set_global('lang', substr(Kohana::config('locale.language.0'), 0, 2));
		// Array with META, JS, CSS and others
		$head['title'] = 'NO TITLE';	// site title
		$head['suffix'] = 'NO SUFFIX';
		$head['meta'] = array();			// fieldname => value
		$head['js'] = array();				// filename
		$head['css'] = array
		(
			'media/css/reset.css'	=> 'all',
			'media/css/index.css'	=> 'all',
		);
		$this->template->set_global('head', $head);
	}

	public function _keep_referrer($current_uri = FALSE) {
		if (!$this->history) return FALSE;
		if ($current_uri === TRUE) {
			$this->session->set($this->config['referrer_key'], url::current(TRUE));
		}
		elseif (FALSE === $this->session->get($this->config['referrer_key'], FALSE)) {
			$this->session->set($this->config['referrer_key'], request::referrer());
		}
	}

	protected function get_referrer() {
		return $this->session->get($this->config['referrer_key']);
	}

}